<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\question\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;

/**
 * 培训题目管理
 * Class User
 * @package app\worker\controller
 */
class Question extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'question';
    protected $table_view = 'view_question';

    /**
     * 培训题目管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {

// array(6) { ["spm"]=> string(10) "m-67-68-69" ["question"]=> string(3) "cnm" ["company"]=> string(2) "wc" ["status"]=> string(1) "0" ["create_at_first"]=> string(10) "2020-08-03" ["create_at_last"]=> string(10) "2020-08-05" }
        // $this->title = '仓库权限管理';
        //var_dump($this->request->param(''));
        $uinfo = $this->getGuserinfo();
        $where1 ='';
        if($uinfo['db1']['authorize']!=1 && $uinfo['db1']['authorize']!=0){
            $check = $uinfo['db2']['companyid']==NULL?:'';
            if(!$check){
                 $where1 = 'companyid = '.$uinfo['db2']['companyid'];
            }         
           
        }
		 $this->title = '考核问题管理';
           $dbconf = $this->getconfig('vister_db');
		 $create_at_first=trim($this->request->param('create_at_first'));
		 	 $create_at_last=trim($this->request->param('create_at_last'));
		 	$where = '';
		 	 if($create_at_first!='' && $create_at_last!=''){
		 	
		 		$create_at_first = strtotime($create_at_first);
                $create_at_last = strtotime($create_at_last)+(3600*24);
                $where = 'createtime between '.$create_at_last.' and '.$create_at_first;

                } 
                $where = $where!=''?$where.' and deletetime is null':' deletetime is null ';
            if($this->request->param('company_id')){
                $companyid = $this->request->param('company_id');
                $where1 =  'companyid = '.$companyid;
            }
		 		$this->_query(Db::connect($dbconf)->table($this->table_view))->where($where1)->like('question,name')->equal('status')->where($where)->order('createtime desc')->page();
            
		 												

    }

    /**
     * 添加培训题目
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        //$this->title = "添加题目";
        $dbconf = $this->getconfig('vister_db');

        $company_list = Db::connect($dbconf)->table('view_company')->select();
        $this->assign('data',[
            /**丢给视图的数据**/
            'companylist'=>$company_list,

        ]);
        $this->assign('Gtikchoice',['A','B','C','D']); 
        //var_dump($this->request->param(''));
        // array(10) { ["spm"]=> string(10) "m-67-68-69" ["open_type"]=> string(5) "modal" ["question"]=> string(3) "zxc" ["companyid"]=> string(0) "" ["optionA"]=> string(3) "cxz" ["optionB"]=> string(3) "ssx" ["optionC"]=> string(3) "xcz" ["optionD"]=> string(3) "saa" ["option_true"]=> string(1) "A" ["status"]=> string(2) "on" } {"code":1,"info":"添加培训题目成功","data":""}
        //exit();
        $uinfo = $this->getGuserinfo();

        if($this->request->param('question')){
            $companyid = $this->request->param('companyid');

            if(!$companyid){
                $companyid = $uinfo['db2']['companyid']?:'';
                if(!$companyid){
                    return $this->error('参数有误,请稍候再试','');
                }
            }
            $option_true = $this->request->param('option_true');
            // 0启用 1禁用
            $status = $this->request->param('status')=='on'?0:1;
            $options_tik = ['A','B','C','D'];

            $options_in_arr = [];
            $true_index = 0;
            foreach ($options_tik as $key => $value) {

                if($this->request->param('option'.$value)==""){continue;}

                # code...
                $count_arr = count($options_in_arr);
                $new_value = $options_tik[$count_arr];


               $options_in_arr[$true_index]['tik'] = $new_value;

                if($value==$option_true){
                    $option_true = $key;
                }

                $options_in_arr[$true_index]['value'] = "".$key;
                $options_in_arr[$true_index]['name'] = $this->request->param('option'.$value);
                $true_index++;

            }
            if (preg_match ("/^[A-Za-z]/", $option_true)) {
                    $this->error('参数错误');
            }
            // var_dump($options_arr);
            $data = [
    
                'companyid' => $companyid,
                'question' => $this->request->param('question'),
                'options' => json_encode($options_in_arr),
                'answer' => $option_true,
                'createtime' => time(),
                'status' => 0,
            ];
            $res = Db::connect($dbconf)->table($this->table)->insert($data);
            if($res){
             //return $this->redirect('index');
             return $this->success('添加培训题目成功','');
                
            }else{
                return $this->error('添加培训题目失败,请稍后再试','');
                }
        }
        $this->_form(Db::connect($dbconf)->table($this->table_view), 'form');
    }


    /**
     * 修改培训题目
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        //var_dump($this->request->param(''));
        
        $dbconf = $this->getconfig('vister_db');

        $company_list = Db::connect($dbconf)->table('view_company')->select();
        $assigndata['companylist'] = $company_list;

        $this->assign('Gtikchoice',['A','B','C','D']);
        if($this->request->param('id')){
            $question_info = Db::connect($dbconf)->table($this->table_view)->where(['id'=>$this->request->param('id')])->find();
            if($question_info){
                $question_info['options'] = json_decode($question_info['options'],true);
            }
            $assigndata['questioninfo'] = $question_info;
        }

        /**丢给视图的数据**/
        $this->assign('data',$assigndata);

        if($this->request->param('question')){
            if(!$this->request->param('companyid')){$this->error('参数错误');}
            $id = $this->request->param('id');
            $options_arr = ['A','B','C','D'];
            $where = 'id ='.$this->request->param('companyid');
            $companyinfo = Db::connect($dbconf)->table('view_company')->where($where)->find();
            if(!$companyinfo){return $this->success('公司不存在');exit();}
            $companyid = $companyinfo['id'];
             // 题目格式 : ["options"]=> string(77) "[{"value":"0","name":"答1","tik":"A"},{"value":"1","name":"答2","tik":"B"}]"
             $options_in_arr = [];
             $true_index = 0;
            foreach ($options_arr as $key => $value) {
                # code...
                if($this->request->param('options'.$value)==''){
                    continue;
                }

                $count_arr = count($options_in_arr);
                $new_value = $options_arr[$count_arr];

                $options_in_arr[$true_index]['tik'] = $new_value;
                if($value == $this->request->param('option_true')){
                    $answer = $key;
                }
                // var_dump($key);
                // var_dump($answer);
                $options_in_arr[$true_index]['value'] = "".$key;
                $options_in_arr[$true_index]['name'] = $this->request->param('options'.$value);
                $true_index++;


            }
            $options_in_arr = json_encode($options_in_arr);


            $data = [

                'question' => $this->request->param('question'),
                'companyid' => $companyid,
                'options' => $options_in_arr,
                'answer' => $answer,
                'createtime' => time(),
                // 0启用 1禁用
                'status' => $this->request->param('status')=='on'?0:1,

            ];
            $where = [
                'id' => $id
            ];

            $res= Db::connect($dbconf)->table($this->table)->where($where)->data($data)->update();
          //$this-> _save(Db::connect($dbconf)->table($this->table), $data, $field = '', $where);
           if(!$res){return $this->error('题目修改失败,请稍后再试','');}
           $this->success('题目修改成功','');

        }
        // $data = @Db::connect($dbconf)->table($this->table_view)->where('id',$id)->find();
        $this->_form(Db::connect($dbconf)->table($this->table_view), 'form');


        // return $this->fetch('index',[
        //     'list'=> $data,
        // ]);
		


    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        if ($this->request->isGet()) {
            $where = ['status' => '1', 'is_deleted' => '0'];
            $this->auths = Db::name('company_user_auth')->where($where)->order('sort desc,id desc')->select();
            array_unshift($this->auths, ['id' => '0', 'title' => '所有权限', 'path' => '/']);
            $data['svn_authorize'] = isset($data['svn_authorize']) ? explode(',', $data['svn_authorize']) : [];
        } else {
            if (isset($data['svn_authorize']) && is_array($data['svn_authorize'])) {
                $data['svn_authorize'] = join(',', $data['svn_authorize']);
            } else {
                $data['svn_authorize'] = '';
            }
            // $macs = [];
            // foreach (explode(PHP_EOL, preg_replace("/\s+/", PHP_EOL, trim($data['mobile_macs']))) as $mac) {
            //     if (DataService::applyMacValue($mac)) $macs[] = $mac;
            // }
            // $data['mobile_macs'] = join(PHP_EOL, array_unique($macs));
        }
    }

    /**
     * 更改培训题目状态
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function state()
    {
         $dbconf = $this->getconfig('vister_db');

        $this->_save(Db::connect($dbconf)->table($this->table), ['status' => $this->request->param('status')],'',['id' => $this->request->param('id')]);
    }

    /**
     * 删除培训题目
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $dbconf = $this->getconfig('vister_db');
		// $this->_delete($this->table);
		if($this->request->isPost()){      
		$id=trim($this->request->param('id'));

		// $data=Db::connect($dbconf)->table($this->table)->where("id in ($id)")->delete();
        $data = $this->_save(Db::connect($dbconf)->table($this->table), ['deletetime' =>time()]); 
		if($data){
			$this->success('题目删除成功！');
		}
		}
    }

}
